<script setup name="printConfig">
import {
  GetDetailsAPI,
  GetDailtAPI,
  GetConfigAPI,
  GetListAPI,
  DelDataAPI,
  AddDataAPI,
  EditDataAPI
} from '@/api/system/printConfig'
import Print from './print.vue'
import addForm from './addForm.vue'
import printInitConfig from './printConfig.json'
import { useRouter } from 'vue-router'
const { proxy } = getCurrentInstance()
// 封装 方法 字典查询
const { sys_print_type } = proxy.useDict('sys_print_type')

const router = useRouter()

const formRef = ref(null)

const tableData = ref([])
const ruleForm = ref({})

// 查询条件
const SelectList = ref([
  //   { type: '日期范围' },
  { label: '模板类型', model: 'printType', type: '下拉单选', opt: sys_print_type },
  { label: '模板名称', model: 'printName', type: '输入框' }
])

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10
})

// 状态
const state = reactive({
  rows: [], // 勾选数据
  ids: [], // 勾选id
  title: '', // 弹窗标题
  delDisabled: false, // 禁用 多选
  examineDisabled: false, // 禁用 单选
  isShow: false, // 新增 修改弹窗
  configIsShow: false // 配置弹窗
})

// 勾选列表数据时
const handleSelectionChange = selection => {
  state.rows = selection
  state.ids = selection.map(item => item.printId)

  state.delDisabled = !selection.length
  selection.length <= 0 || selection.length > 1 ? (state.examineDisabled = true) : (state.examineDisabled = false)
}
handleSelectionChange([])

// 新增 弹窗
const add = () => {
  state.title = '新增'
  state.isShow = true
}

// 修改 弹窗
const edit = async id => {
  try {
    proxy.$modal.loading('请稍候...')
    state.title = '修改'
    const { data: res } = await GetDailtAPI(id)
    ruleForm.value = res
    state.isShow = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 配置 弹窗
const config = async val => {
  try {
    proxy.$modal.loading('请稍候...')
    state.title = '配置'
    const res = await GetConfigAPI(val.printId)
    // 如果有 用数据库 否则初始模板
    ruleForm.value.tableData = res.msg ? JSON.parse(res.msg) : printInitConfig
    ruleForm.value.id = val.printId
    const resp = await GetDetailsAPI(val.printCorrelation)
    ruleForm.value.elementList = resp.data
    await ruleForm.value.elementList.forEach(item => {
      item.tid = item.tid + item.options.textType
      if (item.icon == 'erweima') {
        item.options.height = 50
        item.options.width = 50
        // item.options.lineHeight = 50
      } else if (item.icon == 'tiaoxingma') {
        item.options.height = 20
        item.options.width = 120
      } else {
        item.options.height = 20
      }
    })

    state.configIsShow = true
  } catch (err) {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 查看 弹窗
const dxamine = async id => {
  try {
    proxy.$modal.loading('请稍候...')
    state.title = '查看'
    const { data: res } = await GetDailtAPI(id)
    ruleForm.value = res
    state.isShow = true
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 新增提交后台
const addSub = async () => {
  const res = await formRef.value.submit()
  if (!res) return
  try {
    state.btnLoading = true
    await AddDataAPI(res)
    getList()
    close()
    proxy.successMsg('新增成功')
  } catch {
  } finally {
    state.btnLoading = false
  }
}

// 修改提交后台
const editSub = async () => {
  const res = await formRef.value.submit()
  if (!res) return
  try {
    state.btnLoading = true
    await EditDataAPI(res)
    getList()
    close()
    proxy.successMsg('修改成功')
  } catch {
  } finally {
    state.btnLoading = false
  }
}

// 配置修改保存
const configEdit = async val => {
  proxy.$modal.loading('请稍候...')
  try {
    await EditDataAPI({
      printId: ruleForm.value.id,
      printCompile: val
    })
    getList()
    close()
    proxy.successMsg('配置成功')
  } catch {
  } finally {
    proxy.$modal.closeLoading()
  }
}

// 删除
const remove = async val => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  await DelDataAPI(val ? val : state.ids.join(','))
  getList()
  close()
  proxy.successMsg('删除成功')
}

const close = () => {
  state.isShow = false
  state.configIsShow = false
  ruleForm.value = {}
}
// 条件查询
const selectSubmit = Obj => {
  for (let KEY in Obj) {
    query[KEY] = Obj[KEY]
  }
  getList()
}

// 获取列表
const getList = async () => {
  state.loading = true
  try {
    const res = await GetListAPI(query)
    tableData.value = res.rows
    state.total = res.total
  } catch (error) {
  } finally {
    state.loading = false
  }
}
getList()
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <div>
        <el-button type="primary" v-hasPermi="['system:printConfig:add']" @click="add">新增</el-button>
        <!-- <el-button
          type="primary"
          v-hasPermi="['system:printConfig:add']"
          @click="router.push(`/system/printConfig-data`)"
          >配置</el-button
        > -->

        <el-button
          type="danger"
          :disabled="state.delDisabled"
          v-hasPermi="['system:printConfig:remove']"
          @click="remove(false)"
          >删除</el-button
        >
      </div>
      <el-table
        v-loading="state.loading"
        stripe
        border
        :data="tableData"
        style="margin-top: 20px"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" width="70" type="index" />
        <el-table-column label="模板编号" prop="printCode" width="220" show-overflow-tooltip />
        <el-table-column label="模板名称" prop="printName" width="220" show-overflow-tooltip />
        <el-table-column label="模板类型" prop="printTypeDict" width="auto" show-overflow-tooltip />
        <el-table-column label="关联位置" prop="printCorrelationName" width="auto" show-overflow-tooltip />
        <el-table-column label="创建人" prop="createBy" width="auto" show-overflow-tooltip />
        <el-table-column label="创建时间" prop="createTime" width="auto" show-overflow-tooltip />
        <el-table-column label="操作" align="center" width="300" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <!--  -->
              <el-link
                type="primary"
                text="字段配置"
                v-hasPermi="['system:printConfig:config']"
                @click="
                  router.push(
                    `/system/printConfig-data?id=${scope.row.printId}&printCorrelation=${scope.row.printCorrelation}`
                  )
                "
              >
              </el-link>
              <el-link
                type="primary"
                text="配置内容"
                v-hasPermi="['system:printConfig:configCount']"
                @click="
                  router.push(
                    `/system/printConfig-print?id=${scope.row.printId}&printCorrelation=${scope.row.printCorrelation}`
                  )
                "
              >
              </el-link>

              <!-- <el-link
                type="primary"
                text="配置内容"
                v-hasPermi="['system:printConfig:config']"
                @click="config(scope.row)"
              /> -->

              <el-link
                type="primary"
                text="查看"
                v-hasPermi="['system:printConfig:query']"
                @click="dxamine(scope.row.printId)"
              />
              <el-link
                type="primary"
                text="修改"
                v-hasPermi="['system:printConfig:edit']"
                @click="edit(scope.row.printId)"
              />
              <el-link
                type="primary"
                text="删除"
                v-hasPermi="['system:printConfig:remove']"
                @click="remove(scope.row.printId)"
              />
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="state.total > 0"
        :total="state.total"
        v-model:page="query.pageNum"
        v-model:limit="query.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 新增 修改 查看 -->
    <p-XiaoheDialog :dialogVisible="state.isShow" :title="state.title" @close="close" width="60%">
      <template #body>
        <addForm ref="formRef" :title="state.title" :data="ruleForm" :disabled="state.title == '查看'" />
        <Btn @submit="state.title == '新增' ? addSub() : editSub()" @close="close" />
      </template>
    </p-XiaoheDialog>
    <p-XiaoheDialog :dialogVisible="state.configIsShow" title="配置-(Ctrl+Z可撤回上一步哦)" @close="close" width="90%">
      <template #body>
        <Print @exportJson="configEdit" :template-data="ruleForm.tableData" :elementData="ruleForm.elementList" />
      </template>
    </p-XiaoheDialog>
  </div>
</template>
<style lang="scss" scoped></style>
